package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.AbstractAction;

import svgedit.gui.Frame;
import svgedit.gui.actions.ViewListener.ShapeType;
import svgedit.svg.SVGElement;
import svgedit.svg.SVGGroup;

/**
 * Action to ungroup selected SVGGroups into separate SVGElements.
 * The elements to be grouped are all listed in the SelectedElements in the view
 * @see svgedit.svg.SVGGroup#SVGGroup(ArrayList)
 * @see svgedit.svg.SVGElement
 * @see svgedit.gui.actions.SelectedElements
 * @see svgedit.gui.View
 * 
 */
public class UnGroupAction extends AbstractAction implements ActionListener
{
	private static final long serialVersionUID = 3235277854277937599L;

	public UnGroupAction()
	{
		super("Un-Group");
	}

	/**
	 * Here we get the elements currently selected from SelectedElements and
	 * ungroup all the SVGGroups that are currently selected. This action
	 * iterates over all the elements in the selections and if it is a group
	 * calls the ungroup method on it
	 * @see svgedit.svg.SVGGroup#ungroup()
	 */
	@Override
	public void actionPerformed(ActionEvent e)
	{
		Frame frame = Frame.getFrame();
		frame.getView().getViewListener().setShapeType(ShapeType.UNGROUP);
		//frame.getDocument().getRootGroup().write(5);

		if (frame.getView().getSelected().includesGroups())
		{
			for (SVGElement group : frame.getView().getSelected().getList())
			{
				if (group instanceof SVGGroup)
				{
					((SVGGroup) group).ungroup();
				}
			}
		}

		// reset shape tool and repaint the view
		frame.getView().getViewListener().setShapeType(ShapeType.NONE);
		frame.getView().repaint();
		frame.modifiedTitle(true);
		frame.getView().getSelected().clear();
		
		frame.enableGroupMenuItem(false);
		frame.enableUnGroupMenuItem(false);
		frame.enableDeleteMenuItem(false);
		
		// debug to console
		//frame.getDocument().getRootGroup().write(5);
	}
}
